package reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import reggie.common.R;
import reggie.dto.DishDto;
import reggie.entity.Category;
import reggie.entity.Dish;
import reggie.entity.DishFlavor;
import reggie.service.CategoryService;
import reggie.service.DishFlavorService;
import reggie.service.DishService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        //获取key
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();

        //根据key删除redis里面的缓存
        redisTemplate.delete(key);

        return R.success("添加菜品成功!");
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //创建分页对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);

        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

//        List<DishDto> list = records.stream().map((item)->{
//
//            DishDto dishDto = new DishDto();
//
//            BeanUtils.copyProperties(item,dishDto);
//
//            Long categoryId = item.getCategoryId();//分类id
//
//            //根据id查询分类对象
//            Category category = categoryService.getById(categoryId);
//
//            if (category != null) {
//                String categoryName = category.getName();
//                dishDto.setCategoryName(categoryName);
//            }
//            return dishDto;
//        }).collect(Collectors.toList());

        List<DishDto> list = new ArrayList<>();

        for (Dish dish : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);

            Long categoryId = dish.getCategoryId();

            Category category = categoryService.getById(categoryId);

            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            list.add(dishDto);
        }


        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlover(id);

        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);

        //获取key
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();

        //根据key删除redis里面的缓存
        redisTemplate.delete(key);

        return R.success("新增菜品成功！");
    }

    /**
     * 批量停售/起售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status,@RequestParam List<Long> ids) {
//        log.info("_______________________________________________________________________________");
//
//        log.info(String.valueOf(status),ids);

        if (!ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                Long id = ids.get(i);

                UpdateWrapper<Dish> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id",id);
                updateWrapper.set("status",status);

                dishService.update(updateWrapper);
            }
        }

        return R.success("操作成功！");

    }

    /**
     * 批量/单个删除菜品以及包含的口味信息
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
//        if (!ids.isEmpty()) {
//            for (int i = 0; i < ids.size(); i++) {
//                Long id = ids.get(i);
//                dishService.removeById(id);
//            }
//        }

        dishService.deleteWithFlavor(ids);

        return R.success("删除成功！");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        List<DishDto> dishDtos = null;

        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1

        //从redis中获取查询数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtos != null) {
            return R.success(dishDtos);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtos = list.stream().map((item)->{

            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();

            lambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());

            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(dishFlavors);

            Category category = categoryService.getById(item.getCategoryId());

            dishDto.setCategoryName(category.getName());

            return dishDto;
        }).collect(Collectors.toList());

        //将新查询到的集合存入redis中
        redisTemplate.opsForValue().set(key,dishDtos);

        return R.success(dishDtos);
    }

}
